<?php

/**
 * 微信小程序工具类
 * @author Reer
 * @email reer_shu_re@163.com
 */
namespace app\common\utils;


use app\common\bean\ListMap;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;
use Exception;

class AppletWechatUtil extends BaseUtil
{
    static $_self = null;

    /**@var Application $app*/
    private static $app;
    public static function getInstance(){
        if(empty(self::$_self)){
            self::$_self = new AppletWechatUtil();
            $config = [
                'app_id' => config('project.APPLET_WECHAT.APPID'),
                'secret' => config('project.APPLET_WECHAT.APPSECRET'),
                'response_type' => 'array',
            ];
            self::$app = Factory::miniProgram($config);
        }
        return self::$_self;
    }


    /**
     * @param $code
     * @return ListMap
     * @throws Exception
     */
    public function oauth($code)
    {
        $result = self::$app->auth->session($code);
        $listMap = new ListMap();
        $listMap->setData($result);
        return $listMap;
    }

    /**
     * @param ListMap $resultMap
     * @return ListMap
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     */
    public function decryptedData(ListMap $resultMap)
    {
        $listMap = new ListMap();
        $decryptedData = self::$app->encryptor->decryptData($resultMap->getParameter("session_key"), $resultMap->getParameter("iv"), $resultMap->getParameter("encryptedData"));
        $listMap->setData($decryptedData);
        return $listMap;
    }
}